package com.example.sunmiv1.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.CreditUserAdapter;
import com.example.sunmiv1.base.BaseActivity;
import com.example.sunmiv1.dialog.SetCreditMoneyDialog;
import com.example.sunmiv1.entity.CreditUserListInfo;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CreditUserActivity extends BaseActivity {


    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.creditUser_allMoney)
    TextView creditUserAllMoney;
    @BindView(R.id.creditUser_allRepayMoney)
    TextView creditUserAllRepayMoney;
    @BindView(R.id.creditUser_monthMoney)
    TextView creditUserMonthMoney;
    @BindView(R.id.creditUser_monthRepayMoney)
    TextView creditUserMonthRepayMoney;
    @BindView(R.id.creditUser_todayMoney)
    TextView creditUserTodayMoney;
    @BindView(R.id.creditUser_todayRepayMoney)
    TextView creditUserTodayRepayMoney;
    @BindView(R.id.creditUser_addUser)
    TextView creditUserAddUser;
    @BindView(R.id.creditUser_setMoney)
    TextView creditUserSetMoney;
    @BindView(R.id.creditUser_deleteUser)
    TextView creditUserDeleteUser;
    @BindView(R.id.creditUser_listView)
    PullToRefreshListView creditUserListView;
    @BindView(R.id.creditUser_cancel)
    TextView creditUserCancel;
    @BindView(R.id.creditUser_confirm)
    TextView creditUserConfirm;
    @BindView(R.id.creditUser_operaLin)
    LinearLayout creditUserOperaLin;

    private int page = 1;
    private Context context;
    private CreditUserListInfo listInfo;
    private List<CreditUserListInfo.DataBean.ListBean> list = new ArrayList<>();
    private CreditUserAdapter creditUserAdapter;
    private LoadingDialog loadingDialog;
    private int selectIndex;
    private int batchType = 0;
//    private boolean type = false;
    private ACache aCache;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    list.addAll(listInfo.getData().getList());
                    setCreditUserAdapter();
                    break;
                case 2:
                    break;
            }
        }
    };


    @Override
    protected void initView() {
        setContentView(R.layout.activity_credit_user);
        ButterKnife.bind(this);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        titleTitle.setText(R.string.creditUserTitle);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        initList();
        getStoreStatistics();
    }

    @Override
    protected void initListener() {
        creditUserListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                initList();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                getArrearageList();
            }
        });
    }

    private void initList() {
        page = 1;
        list.clear();
        setCreditUserAdapter();
        getArrearageList();
    }

    @OnClick({R.id.title_back, R.id.creditUser_addUser, R.id.creditUser_setMoney, R.id.creditUser_deleteUser,
            R.id.creditUser_cancel, R.id.creditUser_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.creditUser_addUser:
//                if(!"3".equals(aCache.getAsString("userType"))){
//                    Toast.makeText(context, "只有收銀員可以操作", Toast.LENGTH_SHORT).show();
//                    return;
//                }
                Intent intent = new Intent(context, AddCreditUserActivity.class);
                startActivity(intent);
                break;
            case R.id.creditUser_setMoney:
                for (CreditUserListInfo.DataBean.ListBean bean : list) {
                    bean.setCheck(false);
                }
                batchType = 1;
                creditUserAdapter.setType(true);
                creditUserConfirm.setText(R.string.settingQuota);
                creditUserSetMoney.setBackgroundResource(R.color.ffe8ea);
                creditUserDeleteUser.setBackgroundResource(R.color.f6f6f6);
                creditUserOperaLin.setVisibility(View.VISIBLE);
                break;
            case R.id.creditUser_deleteUser:
                for (CreditUserListInfo.DataBean.ListBean bean : list) {
                    bean.setCheck(false);
                }
                batchType = 2;
                creditUserAdapter.setType(true);
                creditUserConfirm.setText(R.string.delete);
                creditUserDeleteUser.setBackgroundResource(R.color.ffe8ea);
                creditUserSetMoney.setBackgroundResource(R.color.f6f6f6);
                creditUserOperaLin.setVisibility(View.VISIBLE);
                break;
            case R.id.creditUser_cancel:
                creditUserAdapter.setType(false);
                creditUserOperaLin.setVisibility(View.GONE);
                creditUserDeleteUser.setBackgroundResource(R.color.f6f6f6);
                creditUserSetMoney.setBackgroundResource(R.color.f6f6f6);
                break;
            case R.id.creditUser_confirm:
                if (batchType == 1) {
                    JSONArray jsonArray = new JSONArray();
                    for (CreditUserListInfo.DataBean.ListBean listBean : list) {
                        if (listBean.isCheck()) {
                            JSONObject ids = new JSONObject();
                            try {
                                ids.put("credit_id", listBean.getCredit_id());
                                ids.put("quota", listBean.getQuota());
                                jsonArray.put(ids);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    if (jsonArray.length() == 0) {
                        Toast.makeText(context, "請先選擇用戶", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    SetCreditMoneyDialog.newInstance(jsonArray, 2)
                            .callback(o -> {
                                setUserQuota(2, o.toString());
                            })
                            .startShow(getSupportFragmentManager(), "")
                            .setCancelable(false);
                } else {
                    deleteCreditUser(2);
                }
                break;
            default:
                break;
        }
    }

    private void setCreditUserAdapter() {
        if (creditUserAdapter == null) {
            creditUserAdapter = new CreditUserAdapter(list);
            creditUserListView.setAdapter(creditUserAdapter);
        } else {
            creditUserAdapter.notifyDataSetChanged();
        }
        creditUserAdapter.setCallBack((index, type) -> {
            selectIndex = index;
            switch (type) {
                case 1:
//                    if(!"3".equals(aCache.getAsString("userType"))){
//                        Toast.makeText(context, "只有收銀員可以操作", Toast.LENGTH_SHORT).show();
//                        return;
//                    }
                    JSONArray jsonArray = new JSONArray();
                    JSONObject id = new JSONObject();
                    try {
                        id.put("credit_id", list.get(index).getCredit_id());
                        jsonArray.put(id);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    SetCreditMoneyDialog.newInstance(jsonArray, 1)
                            .callback(o -> {
                                setUserQuota(1, o.toString());
                            })
                            .startShow(getSupportFragmentManager(), "")
                            .setCancelable(false);
                    break;
                case 2:
//                    DeleteUseDialog.newInstance()
//                            .startShow(getFragmentManager(), "")
//                            .callback(o -> {
                    deleteCreditUser(1);
//                            })
//                            .setCancelable(false);
                    break;
                default:
                    break;
            }
        });
    }

    /**
     * 獲取賒賬人員列表
     */
    private void getArrearageList() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("state", "");//還款狀態 1已結清 2未結清
            jsonObject.put("search", "");
            jsonObject.put("start_time", "");
            jsonObject.put("end_time", "");
            if("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("editor_type", "1");
            }else{
                jsonObject.put("editor_type", "2");
            }//操作場景 1收銀員 2後臺
            jsonObject.put("page", page);
            jsonObject.put("limit", "20");
            jsonObject = Tools.createParameterCode(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(context, Common.GET_CREDIT_USER_LIST, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                loadingDialog.dismiss();
                creditUserListView.onRefreshComplete();
                try {
                    JSONObject json = new JSONObject(text);
                    if (json.getInt("status") == 1) {
                        listInfo = GsonUtils.JsonToBean(text, CreditUserListInfo.class);
                        Message msg = new Message();
                        msg.what = 1;
                        handler.sendMessage(msg);
                    } else {
                        setCreditUserAdapter();
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
                creditUserListView.onRefreshComplete();
            }
        });
    }

    /**
     * 獲取門店賒賬統計
     */
    private void getStoreStatistics() {
        JSONObject jsonObject = new JSONObject();
        jsonObject = Tools.createParameterCode(jsonObject);
        HttpUtils.post(context, Common.GET_STORE_STATISTICS, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                try {
                    JSONObject json = new JSONObject(text);
                    if (json.getInt("status") == 1) {
                        JSONObject data = json.getJSONObject("data");
                        JSONObject total = data.getJSONObject("total");
                        JSONObject month = data.getJSONObject("month");
                        JSONObject today = data.getJSONObject("today");
                        creditUserAllMoney.setText("$" + total.getString("money"));
                        creditUserAllRepayMoney.setText("$" + total.getString("wait_money"));
                        creditUserMonthMoney.setText("$" + month.getString("credit_money"));
                        creditUserMonthRepayMoney.setText("$" + month.getString("wait_money"));
                        creditUserTodayMoney.setText("$" + today.getString("repayment_money"));
                        creditUserTodayRepayMoney.setText("$" + today.getString("wait_money"));
                    } else {
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        creditUserAllMoney.setText("$0");
                        creditUserAllRepayMoney.setText("$0");
                        creditUserMonthMoney.setText("$0");
                        creditUserMonthRepayMoney.setText("$0");
                        creditUserTodayMoney.setText("$0");
                        creditUserTodayRepayMoney.setText("$0");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

    /**
     * 設置額度
     * type:1.設置個人額度 2.批量設置額度
     */
    private void setUserQuota(int type, String money) {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        try {
            if (type == 1) {
                JSONObject id = new JSONObject();
                id.put("credit_id", list.get(selectIndex).getCredit_id());
                id.put("quota", money);
                jsonArray.put(id);
            } else {
                for (CreditUserListInfo.DataBean.ListBean listBean : list) {
                    if (listBean.isCheck()) {
                        JSONObject id = new JSONObject();
                        id.put("credit_id", listBean.getCredit_id());
                        id.put("quota", money);
                        jsonArray.put(id);
                    }
                }
            }
            jsonObject.put("arr", jsonArray);
            if("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("editor_type", "1");
            }else{
                jsonObject.put("editor_type", "2");
            }
            jsonObject = Tools.createParameterCode(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(context, Common.SET_USER_QUOTA, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                loadingDialog.dismiss();
                try {
                    JSONObject json = new JSONObject(text);
                    Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (json.getInt("status") == 1) {
                        initList();
                        creditUserAdapter.setType(false);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

    /**
     * 刪除賒賬用戶
     */
    private void deleteCreditUser(int type) {
        loadingDialog.show();
        JSONArray ids = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        try {
            if (type == 1) {
                JSONObject id = new JSONObject();
                id.put("credit_id", list.get(selectIndex).getCredit_id());
                ids.put(id);
            } else {
                for (CreditUserListInfo.DataBean.ListBean listBean : list) {
                    if (listBean.isCheck()) {
                        JSONObject id = new JSONObject();
                        id.put("credit_id", listBean.getCredit_id());
                        ids.put(id);
                    }
                }
            }
            jsonObject.put("ids", ids);
            if("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("editor_type", "1");
            }else{
                jsonObject.put("editor_type", "2");
            }
            jsonObject = Tools.createParameterCode(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(context, Common.DELETE_CREDIT_USER, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                loadingDialog.dismiss();
                try {
                    JSONObject json = new JSONObject(text);
                    Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (json.getInt("status") == 1) {
                        if (type == 1) {
                            list.remove(selectIndex);
                            creditUserAdapter.setType(false);
                        } else {
                            initList();
                        }
                        if (json.has("defeatArr")) {
                            String msg = "";
                            JSONArray info = json.getJSONArray("defeatArr");
                            for (int i = 0; i < info.length(); i++) {
                                msg = msg + info.getString(i) + "\n";
                            }
                            Toast.makeText(context, msg, 5).show();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
            }
        });
    }

}
